package com.weir.workdemo.work01.limit;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author weir
 */
@Slf4j
@Aspect
@Component
@SuppressWarnings("UnstableApiUsage")
public class LimitAop {

    private final Map<String, RateLimiter> limiterCache = new ConcurrentHashMap<>();


    @Around(value = "@annotation(com.weir.workdemo.work01.limit.Limit)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Limit limit = signature.getMethod().getAnnotation(Limit.class);

        RateLimiter limiter = getRateLimiter(limit);

        if (!limiter.tryAcquire()) {
            log.warn("获取令牌[{}:{}]失败", limit.key(), limiter.getRate());
            responseFail(limit.description());
            return null;
        }
        log.info("获取令牌[{}:{}]成功", limit.key(), limiter.getRate());
        return joinPoint.proceed();
    }

    private RateLimiter getRateLimiter(Limit limit) {
        String key = limit.key();
        RateLimiter limiter;
        if (!limiterCache.containsKey(key)) {
            limiter = RateLimiter.create(limit.qps());
            limiterCache.put(key, limiter);
        } else {
            limiter = limiterCache.get(key);
        }
        return limiter;
    }

    /**
     * 直接向前端抛出异常
     *
     * @param msg 提示信息
     */
    private void responseFail(String msg) {
        HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
        assert response != null;
        log.warn("responseFail:{}", msg);
        response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
    }
}
